package ws

import (
	"fmt"
	"net/http"
	"path/filepath"
	"power/core/localwrap"
	"power/ws/powerws"
	"strconv"

	"github.com/RocksonZeta/hubx"
)

var log = localwrap.GetLogger().Fork("combat/ws", "")

func serveHome(w http.ResponseWriter, r *http.Request) {
	log.Trace().Str("url", r.URL.String()).Send()
	if r.URL.Path != "/" {
		http.Error(w, "Not found", http.StatusNotFound)
		return
	}
	if r.Method != "GET" {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}
	http.ServeFile(w, r, "play.html")
}

func GetUserByToken(token string) powerws.User {
	return powerws.User{}
}

func servePowerWs(w http.ResponseWriter, r *http.Request) {
	log.Trace().Func("serveGameWs").Str("url", r.URL.String()).Send()
	id, err := strconv.Atoi(filepath.Base(r.URL.Path))
	if err != nil {
		w.WriteHeader(400)
		w.Write([]byte("game's id should be an integer."))
		return
	}
	actor, err := powerws.GetOrNewPowerNetwork(id)
	if err != nil {
		w.WriteHeader(500)
		w.Write([]byte("create game failed"))
		return
	}
	token := r.URL.Query().Get("token")
	user := GetUserByToken(token)
	upgrader := hubx.DefaultUpgrader()
	upgrader.CheckOrigin = func(r *http.Request) bool {
		return true
	}
	// check user
	hubx.ServeWs(actor.Hub(), w, r, upgrader, map[string]interface{}{powerws.PropUser: user})
}
func Start(listen string) {
	log.Info().Func("Start").Str("listen", listen).Send()
	http.HandleFunc("/", serveHome)
	http.HandleFunc("/ws/power/", servePowerWs)
	fmt.Println("Now websocket listening on: ws://localhost" + listen)
	err := http.ListenAndServe(listen, nil)
	if err != nil {
		log.Error().Stack().Err(err).Msg(err.Error())
	}
}
